# -*- coding:utf-8 -*-

# @File     :middleware
# @Author   :Yupeng
# @Date     :2018/10/26 10:25
""""

"""

import logging
import threading
import pytz

from django.conf import settings
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
from rest_framework.authentication import SessionAuthentication
from hte.error.handle import HTEException


# from hte.errors.handlers import HTEException


class HTEExceptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        return response

    def process_exception(self, request, exception):
        import json
        if not isinstance(exception, HTEException) and not isinstance(exception, HTEException):
            raise exception
            # exception = MGEException(MGEError.UNKNOWN_ERROR)
        else:
            logging.error(exception.hte_error.to_dict())

        r = HttpResponse(json.dumps(exception.hte_error.to_dict(), ensure_ascii=False),
                         content_type='application/json; charset=utf-8')
        r.status_code = exception.hte_error.status_code
        return r


class GlobalRequestMiddleware(object):
    _threadmap = {}

    @classmethod
    def get_current_request(cls):
        return cls._threadmap[threading.get_ident()]

    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        self._threadmap[threading.get_ident()] = request

    def process_exception(self, request, exception):
        try:
            del self._threadmap[threading.get_ident()]
        except KeyError:
            pass

    def process_response(self, request, response):
        try:
            del self._threadmap[threading.get_ident()]
        except KeyError:
            pass
        return response


class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        tzname = request.session.get('django_timezone')
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            # timezone.deactivate()    # TODO: 挖个坑，用户设置里面添加时区设置
            tzinfo = pytz.timezone(settings.TIME_ZONE)
            timezone.activate(tzinfo)  # 默认使用系统设置的时区


class CsrfExemptSessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return
